// src/api/class.js
import axios from 'axios'

const request = axios.create({
  baseURL: import.meta.env.DEV ? '/api' : 'http://localhost:8080',
  timeout: 10000
})

request.interceptors.request.use(config => {
  if (config.method === 'post' && !config.headers['Content-Type']) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  }
  return config
})

request.interceptors.response.use(
  res => res.data,
  err => {
    console.error(err)
    return Promise.reject(err)
  }
)

const toParams = obj => {
  const p = new URLSearchParams()
  Object.entries(obj).forEach(([k, v]) => {
    if (v !== '' && v != null) p.append(k, v)
  })
  return p
}

export const classList   = params => request.get('/class/pageList.do', { params: toParams(params) })
export const classAll    = ()      => request.get('/class/list.do')
export const insertClass = data    => request.post('/class/insert.do',  data)
export const updateClass = data    => request.post('/class/update.do',  data)
export const deleteClass = data    => request.post('/class/delete.do',  data)

export const uploadFile = file => {
  const form = new FormData()
  form.append('file', file)
  return request.post('/file/upload.do', form, {
    headers: { 'Content-Type': 'multipart/form-data' }
  })
}